package com.example.security.service;

import com.example.common.system.entity.UserEntity;
import com.example.common.system.service.UserService;
import com.example.common.system.entity.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author chenjf
 * @Date 2022/9/20
 * @Description 自定义userdetailsService
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService, UserDetailsPasswordService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户
        UserEntity user = userService.queryByUserName(username);
        LoginUser sysUser = null;
        if (user != null) {
            sysUser = new LoginUser();
            BeanUtils.copyProperties(user, sysUser);
            if (sysUser.isAdmin()){
                sysUser.setSuperAdmin(1);
            }else {
                sysUser.setSuperAdmin(0);
            }
        }
        if (sysUser == null) {
            throw new UsernameNotFoundException("该账号未找到");
        }
        if (!sysUser.isAccountNonExpired()) {
            throw new UsernameNotFoundException("该账号使用时限已到期");
        }
        if (!sysUser.isEnabled()) {
            throw new UsernameNotFoundException("该账号使用未启用");
        }
        if (!sysUser.isCredentialsNonExpired()) {
            throw new UsernameNotFoundException("该账号用户凭证已过期");
        }
        if (!sysUser.isAccountNonLocked()) {
            throw new UsernameNotFoundException("该账号被锁定");
        }
        sysUser.setRoles(userService.getRolesByUid(sysUser.getId()));
        return sysUser;
    }

    //密码自动升级
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer result = userService.updateByUserName(user.getUsername(), newPassword);

        if (result == 1) {
            ((LoginUser) user).setPassword(newPassword);
        }
        return user;
    }
}
